const codeCollection = require("../models/codeCollection")
const point = require("../models/point")
const menu = require("../models/menu")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
          codeCollection.find({
            UUID: fields.UUID
          }, async (error, doc) => {
                if (error) {
                    res.json({ 'state': false, 'msg': error });
                } else {
                    if(doc.length===0){
                        res.json({ 'state': true, 'msg': [] });
                        return
                    }
                    let return_data = []
                    let menus = await menu.find()
                    for(i=0; i<doc.length; i++) {
                        if(doc[i].pointId!==""){
                            let point_return = {}
                            point_return.type = "point"
                            let point_mes = await point.find({
                                _id: doc[i].pointId
                            }, {
                                title: 1,
                                menu: 1
                            })
                            let menu_ = point_mes[0].menu.split(',')
                            let m = menus.find((e) => {
                                return e.lesson === menu_[0]
                            })
                            point_return.menuTitle = m.menu[menu_[1]].title
                            point_return.menuSubtitle = m.menu[menu_[1]].subtitle[menu_[2]]
                            point_return.collection = doc[i]
                            point_return.title = point_mes[0].title
                            return_data.push(point_return)
                        } else if (doc[i].demoId!=="") {
                            return_data.push({
                                type: "demo",
                                collection: doc[i]
                            })
                        }
                    }
                    res.json({ 'state': true, 'msg': return_data });
                }
            })

        }

    });

});

module.exports = router;